<template>
  <div class="bg">
    <router-view/>
  </div>
</template>
<script>
import browserWS from 'reconnecting-websocket'
import  {pData} from "@/utils/http";
import _ from "lodash";
import dayjs from "dayjs";

let os = require("os");
const {ipcRenderer} = require('electron');
const { exec } = require('child_process');
export default {
  data() {
    return {
      isDev: process.env.NODE_ENV==='development'
    }
  },
  mounted() {
    //this.shutDown()
    // if(!this.isDev){
    //   this.startDownload()
    // }
    this.startDownload()
    this.setIpcEvent()
    this.initWebSocket()
  },
  methods: {
    shutDown() {
      setTimeout(()=>{
        let currentDay=dayjs().format('M-D')
        let currentWeek=dayjs().format('dd')
        console.log(currentWeek);
        if(currentWeek==='六'||currentWeek==='日'){
          if(!holidays.includes(currentDay)){
            console.log('正常周末,关机');
            exec('shutdown /s /t 0', (error, stdout, stderr) => {
              if (error) {
                console.error(`执行出错: ${error}`);
                return;
              }
              console.log(`stdout: ${stdout}`);
              console.error(`stderr: ${stderr}`);
            });
          }else{
            console.log('上班调休');
          }
        }else{
          if(holidays.includes(currentDay)){
            console.log('工作日休息,关机');
            exec('shutdown /s /t 0', (error, stdout, stderr) => {
              if (error) {
                console.error(`执行出错: ${error}`);
                return;
              }
              console.log(`stdout: ${stdout}`);
              console.error(`stderr: ${stderr}`);
            });
          }else{
            console.log('正常上班');
          }
        }
      },shutDownDelay)
    },
    setIpcEvent(){
      // ipcRenderer.once('willBeDownload1', (event, message) => {
      //   console.log('远程和本地有差异，这是同名但大小不一样的情况，正在使用远程数据1', message)
      //   this.formatMediaRemoteData(message)
      // })
      ipcRenderer.on('willBeDownload2', (event, message) => {
        console.log('远程和本地有差异，这是有文件不存在的情况，等待下载中', message)
        //this.formatMediaRemoteData(message)
      })
      ipcRenderer.on('allTheSame', (event, message) => {
        console.log('本地和远程全部一样，已启用本地加载', message)
         this.formatMediaLocalData(message)
      })
      ipcRenderer.on('netWorkTimeOut', (event, message) => {
        console.log('文件下载超时',message)
      })
      ipcRenderer.on('netWorkError', (event, message) => {
        this.$store.commit('setMediaList',message)
        console.log('没有网路，正在使用本地已有资源',message)
      })
      // ipcRenderer.on('sameNameNotSameSize', (event, message) => {
      //   console.log('文件名相同，但大小不同',message)
      // })
      ipcRenderer.on('mainProcessError', (event, message) => {
        console.error('主进程异常错误',message)
      })
    },
    startDownload() {
      ipcRenderer.send('startDownload');
    },
    formatMediaLocalData(message) {
      let tempData = message.map((s, i) => {
        let tempItem = message[i]
        tempItem.timer = s.timer || '5';
        let t = ''
        if (s.img) {
          tempItem.type = 'image'
          t = s.img.split('/')
        } else if (s.video) {
          tempItem.timer = '0.5';
          tempItem.type = 'mp4'
          t = s.video.split('/')
        }
        tempItem.finallyUrl = 'local-video://media/' + t[t.length - 1]
        return tempItem
      })
      this.$store.commit('setMediaList',_.orderBy(tempData, ['ordernum'], 'asc'))
    },
    // formatMediaRemoteData(data){
    //     let temp = []
    //     data.forEach((s, i) => {
    //       data[i].timer = s.timer || '5';
    //       if (s.img) {
    //         data[i].type = 'image'
    //         data[i].finallyUrl = s.img
    //       } else if (s.video) {
    //         data[i].type = 'mp4'
    //         data[i].finallyUrl = s.video
    //       }
    //       temp.push(s)
    //     })
    //     this.$store.commit('setMediaList',_.orderBy(temp, ['ordernum'], 'asc'))
    // },
    getMac() {
      let mac = ''
      let networkInterfaces = os.networkInterfaces();
      for (let i in networkInterfaces) {
        for (let j in networkInterfaces[i]) {
          if (networkInterfaces[i][j]["family"] === "IPv4" && networkInterfaces[i][j]["mac"] !== "00:00:00:00:00:00" && networkInterfaces[i][j]["mac"] !== "00:ff:aa:bb:cc:dd" && networkInterfaces[i][j]["address"] !== "127.0.0.1") {
            mac = networkInterfaces[i][j]["mac"]
          }
        }
      }
      console.log('本机的mac地址是', mac.toUpperCase()) //01:02:03:0a:0b:0c
      return mac.toUpperCase()
    },
    initWebSocket() {
      let mac = this.getMac()
      console.log(`请求的socket地址是${pData().socketUrl}${mac}`);
      const ws = new browserWS(pData().socketUrl + mac)
      ws.onopen = () => {
        console.log('连接成功', Date.now())
      }
      ws.onclose = () => {
        console.log('连接关闭', Date.now());
      }


      ws.onmessage = (e) => {
        if (e.data.indexOf('{') > -1 || e.data.indexOf('}') > -1) {
          let data = JSON.parse(e.data)
          if (data.command) {
            switch (data.command) {
              case'reload':
                location.reload()
                break;
              case'screen':
                localStorage.setItem('model', 'screen')
                this.$router.push('/screen')
                break;
              case 'floor':
                localStorage.setItem('model', 'floor')
                this.$router.push('/floor')
                break;
              case 'xuanchuan':
                localStorage.setItem('model', 'xuanchuan')
                this.$router.push('/index')
                break;
            }
          }
        }
      }
    },
  },
  created() {
    const model = localStorage.getItem('model');
    if (model === 'xuanchuan' || model === null) {
      this.$router.push('/index')
    } else if (model === 'floor') {
      this.$router.push('/floor')
    } else if (model === 'screen') {
      this.$router.push('/screen')
    } else if (model === 'test') {
      this.$router.push('/test')
    } else {
      this.$router.push('/index')
    }
  },
}
</script>
<style lang="scss">
.devButton{
  position: absolute;
  width: 100px;
  height: 50px;
  left: 0;
  top: 0;
  background: red;
  z-index: 10;
  text-align: center;
  line-height: 50px;
  cursor: pointer;
}
.bg {
  width: 1920px;
  height: 1080px;
  position: relative;
  color: #fff;
}
</style>